import Vue from "vue";
import Vuex from "vuex";
import { reqGetUsers, reqDelete, reqUpdate } from "../api/users";
//
Vue.use(Vuex);

const state = {
  lists: [],
  total: 0,
  page: 1,
  limit: 5,
};
const getters = {};
const actions = {
  async getUsers({ commit }, { page, limit }) {
    let res = await reqGetUsers(page, limit);
    commit("GETUSERS", { res, page, limit });
  },

  //定义删除
  async deleteOne({ commit }, id) {
    await reqDelete(id);
    let res = await reqGetUsers(this.state.page, this.state.limit);
    commit("DELETEONE", res);
  },

  //修改
  async update({ commit }, { username, nickname, password, id }) {
    let res = await reqUpdate({ username, nickname, password, id });
    if (res.data.code === 20000) {
      let newRes = await reqGetUsers(this.state.page, this.state.limit);
      commit("UPDATE", newRes.data.data.users);
    }
    if (res.data.code === 20002) {
      this.$message({
        message: "用户名已存在",
        type: "warning",
      });
    }
    if (res.data.code === 20001) {
      this.$message({
        message: "服务器故障",
        type: "error",
      });
    }
  },
};
const mutations = {
  GETUSERS(state, { res, page, limit }) {
    state.lists = res.data.data.users;
    state.total = res.data.data.total;
    state.page = page;
    state.limit = limit;
  },
  DELETEONE(state, res) {
    state.lists = res.data.data.users;
  },
  UPDATE(state, res) {
    state.lists = res;
  },
};

const store = new Vuex.Store({
  state,
  actions,
  getters,
  mutations,
});

export default store;
